<template>
  <div ref="chart" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const chart = ref(null);
const chartDom = ref(null);

// 初始化图表
const initChart = () => {
  if (chartDom.value) {
    chart.value = echarts.init(chartDom.value);
    chart.value.setOption(props.options);

    // 添加窗口大小变化监听
    window.addEventListener('resize', resizeChart);
  }
};

// 调整图表大小
const resizeChart = () => {
  if (chart.value) {
    chart.value.resize();
  }
};

// 组件挂载时初始化
onMounted(() => {
  initChart();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chart.value) {
    window.removeEventListener('resize', resizeChart);
    chart.value.dispose();
  }
});

// 监听 options 变化
watch(
    () => props.options,
    (newOptions) => {
      if (chart.value) {
        chart.value.setOption(newOptions);
      }
    },
    { deep: true }
);
</script>